package com.trainoo.alert.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @Auther: zt
 * @Date: 2020/4/10 14:19
 * @Description:
 */
@Service
public class SendSmsService implements IService{

    private static final Logger LOG = LoggerFactory.getLogger(SendSmsService.class);

    @Value("${aliyun.sms.product}")
    private String product;
    @Value("${aliyun.sms.domain}")
    private String domain;
    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.sms.templateCode}")
    private String templateCode;
    @Value("${aliyun.sms.singName}")
    private String singName;
    @Value("${aliyun.sms.toPhones}")
    private String toPhones;


    @Override
    public void alert(String mailData) {
        try {
            //初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);

            //组装请求对象-具体描述见控制台-文档部分内容
            SendSmsRequest request = new SendSmsRequest();
            //必填:待发送手机号
            request.setPhoneNumbers(toPhones);
            //必填:短信签名-可在短信控制台中找到
            request.setSignName(singName);
            //必填:短信模板-可在短信控制台中找到
            request.setTemplateCode(templateCode);
            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            request.setTemplateParam(formatTemplate(mailData));
            //hint 此处可能会抛出异常，注意catch
            acsClient.getAcsResponse(request);

        } catch (ClientException e){
            LOG.error("发送短信告警信息异常", e);
        }
    }

    private String formatTemplate(String mailData) {
        JSONObject data = JSONObject.parseObject(mailData);
        String format = "{\"host\":%S, \"time\":%s, \"rule\":%s}";
        return String.format(format, data.get("host"), data.get("@timestamp"), data.get("rule"));
    }
}
